package com.codrim.cs.data.server.subservice;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Liang.Zhuge on 10/05/2017.
 */
@Service
public class TimeZoneSubService implements SubService {

    /**
     * 将时区数值转换为database的表前缀
     *
     * @param timeZone 时区值, 对应tb_time_zone表中time_diff字段
     * @return database对应时区表前缀
     */
    public String prefixTableNameForTimeZone(int timeZone) {
        if (timeZone > 12 || timeZone < -12) {
            throw new IllegalArgumentException("Time sZone must between -12 and 12");
        }

        if (timeZone >= 0) {
            String format = timeZone >= 10 ? "e%s00" : "e0%s00";
            return String.format(format, timeZone);
        } else {
            String format = timeZone <= -10 ? "w%s00" : "w0%s00";
            return String.format(format, Math.abs(timeZone));
        }
    }

    public String prefixTableNameForTimeZone(ZoneId zoneId) {
        return prefixTableNameForTimeZone(zoneValue(zoneId.getId()));
    }

    private static final Pattern ZONE_ID_REGEX = Pattern.compile("(GMT|UTC|UT)((\\+|-)\\d+).*");

    Integer zoneValue(String zoneId) {
        Matcher matcher = ZONE_ID_REGEX.matcher(zoneId);
        if (!matcher.find()) {
            throw new IllegalArgumentException("Invalid sZone id: " + zoneId);
        }

        System.out.println(matcher.group());
        System.out.println(matcher.group(1));
        return NumberUtils.toInt(matcher.group(2));
    }
}
